package com.example.controller;

import com.example.service.CategoryService;
import com.example.service.CommentService;
import com.example.service.LikeService;

import com.example.domain.Comment;
import com.example.domain.PageResult;
import com.example.domain.Post;
import com.example.domain.User;
import com.example.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.List;
//处理与帖子相关的请求
@Controller
public class PostController {
    @Autowired
    private PostService postService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private LikeService likeService;

    @RequestMapping("/posts")
    public String listPosts() {
        return "main";
    }

    @RequestMapping("/post")
    public String toPostPage() {
        return "post";
    }

    @RequestMapping("/postDetail")
    public String showPostDetail(@RequestParam Integer id, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("USER_SESSION");

        Post post = postService.findById(id);
        List<Comment> comments = commentService.getCommentsByPostId(id);

        // 设置帖子的点赞信息
        if (post != null) {
            post.setLikeCount(likeService.getPostLikeCount(id));
            if (currentUser != null) {
                post.setIsLiked(likeService.isPostLiked(currentUser.getId(), id));
            }
        }

        // 设置评论的点赞信息
        if (comments != null && currentUser != null) {
            setCommentLikeInfo(comments, currentUser.getId());
        }

        request.setAttribute("post", post);
        request.setAttribute("comments", comments);
        return "postDetail";
    }

    // 递归设置评论的点赞信息
    private void setCommentLikeInfo(List<Comment> comments, Integer userId) {
        for (Comment comment : comments) {
            comment.setLikeCount(likeService.getCommentLikeCount(comment.getId()));
            comment.setIsLiked(likeService.isCommentLiked(userId, comment.getId()));

            if (comment.getReplies() != null) {
                setCommentLikeInfo(comment.getReplies(), userId);
            }
        }
    }

    // GET方式的搜索（用于分页链接和直接访问）
    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public String listPostsGet(@RequestParam(defaultValue = "1") int pageNum,
                               @RequestParam(defaultValue = "5") int pageSize,
                               @RequestParam(required = false) String keyword,
                               @RequestParam(required = false) Integer categoryId,
                               HttpServletRequest request) {
        return handleSearch(pageNum, pageSize, keyword, categoryId, request);
    }

    // POST方式的搜索（用于搜索表单提交，解决中文编码问题）
    @RequestMapping(value = "/main/search", method = RequestMethod.POST)
    public String searchPosts(@RequestParam(defaultValue = "1") int pageNum,
                              @RequestParam(defaultValue = "5") int pageSize,
                              @RequestParam(required = false) String keyword,
                              @RequestParam(required = false) Integer categoryId,
                              HttpServletRequest request) {
        return handleSearch(pageNum, pageSize, keyword, categoryId, request);
    }

    // 统一的搜索处理方法
    private String handleSearch(int pageNum, int pageSize, String keyword, Integer categoryId, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("USER_SESSION");

        // 处理关键词，确保中文正确显示
        if (keyword != null) {
            keyword = keyword.trim();
            if (keyword.isEmpty()) {
                keyword = null;
            }
        }

        PageResult<Post> pageResult = postService.findByPage(pageNum, pageSize, categoryId, keyword);

        // 为每个帖子设置点赞信息
        if (pageResult != null && pageResult.getRows() != null) {
            for (Post post : pageResult.getRows()) {
                post.setLikeCount(likeService.getPostLikeCount(post.getId()));
                if (currentUser != null) {
                    post.setIsLiked(likeService.isPostLiked(currentUser.getId(), post.getId()));
                }
            }
        }

        request.setAttribute("pageResult", pageResult);
        request.setAttribute("keyword", keyword);
        request.setAttribute("categoryId", categoryId);
        request.setAttribute("categories", categoryService.findAll());
        return "main";
    }

    @RequestMapping("/posts/ajax")
    @ResponseBody
    public PageResult<Post> listPostsAjax(@RequestParam(defaultValue = "1") int pageNum,
                                          @RequestParam(defaultValue = "5") int pageSize) {
        return postService.findAll(pageNum, pageSize);
    }

    @RequestMapping(value = "/post", method = RequestMethod.GET)
    public String showAddPostPage() {
        return "post";
    }

    @RequestMapping("/post/save")
    public String savePost(Post post, HttpServletRequest request) {
        try {
            post.setUserId(((User) request.getSession().getAttribute("USER_SESSION")).getId());
            post.setStatus("active");
            postService.save(post);
            return "redirect:/main";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "发帖失败");
            return "post";
        }
    }

    @RequestMapping(value = "/post/edit", method = RequestMethod.GET)
    public String showEditPostPage(@RequestParam Integer id, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("USER_SESSION");

        if (currentUser == null) {
            return "redirect:/login";
        }

        Post post = postService.findById(id);
        if (post == null) {
            request.setAttribute("msg", "帖子不存在");
            return "redirect:/user/profile";
        }

        if (!post.getUserId().equals(currentUser.getId())) {
            request.setAttribute("msg", "您只能编辑自己的帖子");
            return "redirect:/user/profile";
        }

        request.setAttribute("post", post);
        return "editPost";
    }

    @RequestMapping(value = "/post/update", method = RequestMethod.POST)
    public String updatePost(Post post, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("USER_SESSION");

        if (currentUser == null) {
            return "redirect:/login";
        }

        try {
            Post originalPost = postService.findById(post.getId());
            if (originalPost == null) {
                request.setAttribute("msg", "帖子不存在");
                request.setAttribute("post", post);
                return "editPost";
            }

            if (!originalPost.getUserId().equals(currentUser.getId())) {
                request.setAttribute("msg", "您只能编辑自己的帖子");
                request.setAttribute("post", post);
                return "editPost";
            }

            post.setUserId(originalPost.getUserId());
            post.setStatus(originalPost.getStatus());

            postService.update(post);
            return "redirect:/user/profile";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "更新失败");
            request.setAttribute("post", post);
            return "editPost";
        }
    }
}
